/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-10-08 09:33:25
 * @LastEditors: ycst
 * @LastEditTime: 2024-10-25 18:04:16
 * @FilePath: \as_water\src\common\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import errorCode from './errorCode';
import { ElMessage, ElMessageBox, ElNotification ,ElLoading} from 'element-plus';
import { getToken } from './token';
import { get, set } from './storage';
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: import.meta.env.VITE_APP_API_URL,
  // 超时
  timeout: 60000
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    console.log('请求拦截器', config)
    NProgress.start();
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === true;
    if (getToken() && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.time = new Date().getTime();
    // 防止数据重复提交
    const oldRequest = get(config.url);
    if (oldRequest && !config.antiShake) {
      // ElNotification.warning({title: '数据正在处理中，请勿重复提交！'})
      NProgress.done();
    }
    if (config.method.toUpperCase() !== 'GET') set(config.url, config.method);
    return config;
  },
  (error) => {
    console.error('request', error);
    Promise.reject(error);
    NProgress.done();
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    console.log('响应拦截器', res)
    NProgress.done();
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const message = res.data.message || errorCode[code] || errorCode['default'];
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data;
    }
    if (code === 401) {
      ElNotification.error({ title: '您的账户信息已过期，请重新登录!' });
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
    } else if (code === 400) {
      ElMessage({ message, type: 'error' });
      return Promise.reject(new Error(message));
    } else if (code !== 200) {
      ElNotification.error({ title: message });
      return Promise.reject('error');
    } else {
      return Promise.resolve(res.data);
    }
  },
  (error) => {
    if (error.status === 403) {
      //无权限
      ElMessage({ message: error.response.data.message ? error.response.data.message : '对不起，您没有该接口访问权限', type: 'error' });
    }
    NProgress.done();

    if (error.status === 401) {
      ElNotification.error({ title: '您的账户信息已过期，请重新登录!' });
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
    }
    let { message } = error;
    if (message === 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      // message = "系统接口请求超时";
      message = null;
    } else if (message.includes('Request failed with status code')) {
      // message = "系统接口" + message.substr(message.length - 3) + "异常";
      message = null;
    }


    if (message) {
      ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
    }
    return Promise.reject(error);
  }
);

let downloadLoadingInstance;
// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' });
  return service
    .post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params);
        }
      ],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config
    })
    .then(async (data) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data], {
          type: 'application/vnd.ms-excel'
        });
        saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
        ElMessage.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      ElMessage.error('下载文件出现错误，请联系管理员！');
      downloadLoadingInstance.close();
    });
}

export default service;
